package com.scalar.forecast.projectSetup.actionCommands;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.scalar.forecast.projectSetup.forms.UserDefinedFieldsForm;
import com.scalar.forecast.projectSetup.dao.UserDefinedFieldsDAO;
import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;

import java.util.HashMap;


/**
 * Processes the request to save the user defined fields
 *
 * Created by Veeru. 
 * Date: Feb 9, 2005
 * Time: 8:30:16 PM 
 */


public class UserDefinedFieldsSaveCommand extends ActionCommand{

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response ) {

        ActionForward actionForward = mapping.findForward( "userDefinedFields" );
        UserDefinedFieldsForm userDefinedFieldsForm = ( UserDefinedFieldsForm )form;

        boolean success = false;

        DBTransaction dbTransaction = null;
        HashMap errors = new HashMap ();
        HashMap info = new HashMap ();
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );


        try {
            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();
            UserDefinedFieldsDAO.saveUserDefinedFieldNames( dbTransaction, "PROJSETUP", userDefinedFieldsForm );
            success = true;

        }catch( Exception e ){
            e.printStackTrace();
        }
        finally {
            if ( success ) {
                try {
                    dbTransaction.commit();
                    info.put( INFO_USER_DEFINED_FIELDS_SAVED_SUCCESSFULLY, null);
                }catch ( Exception e){
                    e.printStackTrace();
                }
            }else {
                try {
                    dbTransaction.rollback();
                } catch( Exception e ){
                    e.printStackTrace();
                }
                errors.put ( ERROR_COULD_NOT_SAVE_USER_DEFINED_FIELDS, null );
            }
        }
        return actionForward;
    }
}
